/*
 * 文件名： WechatWcPayCiticServerRes.java
 * 
 * 工程名称: bis-web
 *
 * Gopay
 *
 * 创建日期： 2016年10月12日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.web.controller.wcpay;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.bis.web.controller.scan.WechatScanServerRes;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayNotifyMsg;
import com.gopay.common.util.TransUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * 微信公众号支付中信渠道异步通知
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2016年10月12日
 */
@Controller
@Scope("prototype")
public class WechatWcPayCiticServerRes extends WcPayBankResBase {

	/**
	 * 定义日志对象
	 */
	private static Log logger = LogFactory.getLog(WechatScanServerRes.class);

	@RequestMapping(value = "/wcPayCiticServerRes")
	protected void execute(HttpServletRequest request, HttpServletResponse response) {
		logger.error("---------------WechatWcPayCiticServerRes  bankback ---------------");
		super.execute(request, response);

	}

	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		String paserXml = parseRequst(request);
		
		WcPayNotifyMsg message = (WcPayNotifyMsg) toBean(paserXml);
		message.setBankOrderId(message.getOut_trade_no());
		/**
		 * 金额转换
		 */
		message.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(message.getTotal_fee())));
		message.setBank(BankConstants.BANK_LOGO_WECHAT);
		message.setBankBusProd(BisBankBusinessProd._18);
		message.setFront(false);
		return message;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		
		WcPayNotifyMsg message =(WcPayNotifyMsg)result.getModel("res");
	    OrderInfo orderInfo =new OrderInfo();
	    if(message!=null){
	    	/**
	    	 * 成功
	    	 */
	        if("0".equals(message.getPay_result())){
	            orderInfo.setOrderId(message.getOrderId());
                orderInfo.setAmt(message.getAmount().toString());
                orderInfo.setNotifyNum("1");
                orderInfo.setPayStatus("00");
                orderInfo.setRetCode("00");
                orderInfo.setRetMsg("");
                orderInfo.setIsNotify(true);
                orderInfo.setBankName("wechat");
	        }else{
	            orderInfo.setOrderId(message.getOrderId());
                orderInfo.setAmt(message.getAmount().toString());
                orderInfo.setNotifyNum("1");
                orderInfo.setPayStatus("01");
                orderInfo.setRetCode("01");
                orderInfo.setRetMsg("");
                orderInfo.setIsNotify(true);
                orderInfo.setBankName("wechat");
	        }
	        
	    }  
		return orderInfo;
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected boolean notifyBank(HttpServletResponse response, OrderInfo orderInfo) {
		 String notifyMsg="";
	    try {
	        response.setContentType("text/html;charset=GBK");
	        if("00".equals(orderInfo.getPayStatus())){
	        	notifyMsg="success";
	        }else{
	        	notifyMsg="fail";
	        }
	        logger.info("notifyBank "+orderInfo.getBankName()+" send content: \n["+notifyMsg +"]");
	        response.setContentLength(notifyMsg.getBytes().length);
            response.getOutputStream().write(notifyMsg.getBytes());
            response.getOutputStream().close();
            return true;
        } catch (IOException e) {
        	logger.info(e.getMessage());
        }
		return true;
	
	}

	/**
	 * 
	 * 功能描述：
	 *
	 * @param request
	 * @return
	 * 
	 * @author 宣广海
	 *
	 * @since 2016年10月12日
	 *
	 * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
	 */
	public String parseRequst(HttpServletRequest request) {
		String body = "";
		ServletInputStream inputStream = null;
		BufferedReader br = null;
		try {
			inputStream = request.getInputStream();
			br = new BufferedReader(new InputStreamReader(inputStream));
			while (true) {
				String info = br.readLine();
				if (info == null) {
					break;
				}
				if (body == null || "".equals(body)) {
					body = info;
				} else {
					body += info;
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.info(e.getMessage());
		} catch (IOException e) {
			logger.info(e.getMessage());
		} finally {
			try {
				if (null != inputStream) {
                    inputStream.close();
                }
				if (null != br) {
                    br.close();
                }
			} catch (IOException e) {
				logger.error("关闭IO流异常： ", e);
			}
		}
		return body;
	}

	public BaseMessage toBean(String request) {
		WcPayNotifyMsg message = new WcPayNotifyMsg();
		XStream xs = new XStream(new DomDriver());
		xs.autodetectAnnotations(true);
		//xs.ignoreUnknownElements();
		xs.toXML(message);
		message = (WcPayNotifyMsg) xs.fromXML(request);
		logger.info("支付响应对象：  " + ToStringBuilder.reflectionToString(message));
		return message;
	}
}
